#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from admincms.models import SchoolOrganizationInfo, HomeQuestionnaireInfo
from bs4 import BeautifulSoup
import math


# Create your views here.
def page_index(request):
    newest_list = get_newest()
    school = get_school()
    announcement_list = get_other(['学校公示', '每日菜谱', '校内新闻'], 4)
    party_list = get_other(['师生党建', '教职工党建'], 5)
    beautiful_list = get_other(['运动会', '集体活动', '黑板报'], 5)
    feedback_list = get_questionnaire_index()
    resp = {
        'newest': newest_list,
        'school': school,
        'announcement': announcement_list,
        'party': party_list,
        'beautiful': beautiful_list,
        'feedback': feedback_list,
    }
    return render(request, "index.html", resp)


@csrf_exempt
def search_list(request):
    search = request.GET.get('search')
    page = request.GET.get('page')
    size = request.GET.get('size')
    if page is None or int(page) < 1 or int(page) > 100:
        page = 1
    if size is None or int(size) < 1 or int(size) > 100:
        size = 15
    page_i = int(page)
    size_i = int(size)
    position = page_i * size_i - size_i
    if search is None or len(search) < 1 or search == 'None':
        sql = f'select * from admincms_schoolarticle order by id desc limit {position}, {size_i}'
        count_sql = 'select count(1) as id from admincms_schoolarticle'
    else:
        sql = f'select * from admincms_schoolarticle where article_title like \'%{search}%\' order by id desc ' \
              f'limit {position}, {size_i}'
        count_sql = f'select count(1) as id from admincms_schoolarticle where article_title like \'%{search}%\''
    searches = SchoolOrganizationInfo.objects.raw(sql)
    cursor = connection.cursor()
    cursor.execute(count_sql)
    total = cursor.fetchone()
    if total[0] > 150:
        total[0] = 150
    result_list = []
    for item in searches:
        category = get_menu_type(item.article_type)
        result_list.append({
            'id': item.id,
            'article_title': item.article_title,
            'article_date': item.article_date,
            'category': category,
        })
    last_page = math.ceil(total[0] / size)
    resp = {
        'current': page_i,
        'last': last_page,
        'pages': range(1, last_page+1),
        'search': search,
        'searches': result_list,
    }
    return render(request, "search_list.html", resp)


# newest_list = [
#     {
#         'article_title': None,
#         'article_img': None,
#         'url': None,
#     }
# ]
def get_newest():
    newest_list = []
    articles = SchoolOrganizationInfo.objects.raw('select * from admincms_schoolarticle '
                                                  'where article_content like \'%<img%\' order by id desc limit 5')
    for article in articles:
        soup = BeautifulSoup(article.article_content, features='html.parser')
        menu_type = get_menu_type(article.article_type)
        newest_list.append({
            'article_title': article.article_title,
            'article_img': 'http://127.0.0.1:8000%s' % soup.find('img').attrs['src'],
            'url': 'http://127.0.0.1:8000/detail/%s/%d' % (menu_type, article.id),
        })
    return newest_list


# article = {
#         'article_preview': None,
#         'article_img': None,
#         'url': None,
# }
def get_school():
    articles = SchoolOrganizationInfo.objects.raw('select * from admincms_schoolarticle where '
                                                  'article_type in (\'学校荣誉\', \'组织机构\') '
                                                  'and article_content like \'%<img%\' order by id desc limit 1')
    if len(articles) > 0:
        soup = BeautifulSoup(articles[0].article_content, features='html.parser')
        menu_type = get_menu_type(articles[0].article_type)
        article_preview = articles[0].article_preview
        if len(article_preview) > 180:
            article_preview[:180] + '...'
        article = {
            'article_preview': article_preview,
            'article_img': 'http://127.0.0.1:8000%s' % soup.find('img').attrs['src'],
            'url': 'http://127.0.0.1:8000/detail/%s/%d' % (menu_type, articles[0].id),
        }
        return article
    else:
        return {}


# other_list = [
#     {
#         'article_title': None,
#         'article_date': None,
#         'url': None,
#     }
# ]
def get_other(article_types, limit):
    other_list = []
    article_type_param = ''
    for article_type in article_types:
        article_type_param += '\'' + article_type + '\'' + ','
    article_type_sql = article_type_param[:-1]
    sql = f'select * from admincms_schoolarticle where article_type in ({article_type_sql}) ' \
          f'order by id desc limit {limit}'
    articles = SchoolOrganizationInfo.objects.raw(sql)
    for article in articles:
        menu_type = get_menu_type(article.article_type)
        other_list.append({
            'article_title': article.article_title,
            'article_date': article.article_date,
            'url': 'http://127.0.0.1:8000/detail/%s/%d' % (menu_type, article.id),
        })
    return other_list


def get_questionnaire_index():
    other_list = []
    articles = HomeQuestionnaireInfo.objects\
        .raw('select * from admincms_schoolarticle where article_type=\'问卷调查\' and article_title not like \'[访客%\' '
             'order by id desc limit 5')
    for article in articles:
        other_list.append({
            'article_title': article.article_title,
            'article_date': article.article_date,
            'url': 'http://127.0.0.1:8000/questionnaire/detail/%d' % (article.id, ),
        })
    return other_list


def get_menu_type(menu_name):
    if menu_name == '组织机构':
        return 'SchoolOrganizationInfo'
    elif menu_name == '学校荣誉':
        return 'SchoolHonorInfo'
    elif menu_name == '联系我们':
        return 'SchoolContactInfo'
    elif menu_name == '教职工党建':
        return 'PartyStaffInfo'
    elif menu_name == '师生党建':
        return 'PartyTeacherInfo'
    elif menu_name == '校内新闻':
        return 'NewsCenterInfo'
    elif menu_name == '学校公示':
        return 'AnnounceCenterInfo'
    elif menu_name == '每日菜谱':
        return 'MenuCenterInfo'
    elif menu_name == '黑板报':
        return 'BeautifulBlackboardInfo'
    elif menu_name == '运动会':
        return 'BeautifulSportInfo'
    elif menu_name == '集体活动':
        return 'BeautifulActivityInfo'
    elif menu_name == '问卷调查':
        return 'HomeQuestionnaireInfo'
    elif menu_name == '意见反馈':
        return 'HomeFeedbackInfo'
    else:
        return ''

